import { Text, View } from '@tarojs/components';
import classNames from 'classnames';
import React, { useEffect, useRef, useState } from 'react';
import './tabs.scss';

const Tabs = ({ tabsList = [], getCurrentTab = null, defaultTab = 0 }) => {
  const [currentTab, setCurrentTab] = useState(defaultTab);
  const hasChanged = useRef(false);

  const setTab = (index) => {
    if (index !== currentTab) {
      if (!hasChanged.current) {
        hasChanged.current = true;
      }
      setCurrentTab(index);
    }
  };

  useEffect(() => {
    if (getCurrentTab && hasChanged.current) {
      getCurrentTab(currentTab);
    }
  }, [currentTab]);

  return (
    <View className="coupon-tabs">
      {tabsList.map((tab, index) => (
        <View
          className={classNames('item', {
            'act customePageBackgroundStyle': currentTab === index,
          })}
          onClick={() => setTab(index)}
          key={tab.label + '_' + index}
        >
          <Text className="label">{tab.label}</Text>
        </View>
      ))}
    </View>
  );
};

export default Tabs;
